import { Injectable } from "@nestjs/common";
import * as OSS from "ali-oss";
import * as fs from "node:fs";

const client = new OSS({
  region: "oss-cn-hangzhou",
  accessKeyId: "LTAI5tFS1ACfWCnwrLhHkPB8",
  accessKeySecret: "Ec9OmNiZrFlFpQlLvpML3OIxyFFVlo",
  bucket: "ai-assistant-client",
  secure: true
});

@Injectable()
export class OssFileService {
  constructor() {
  }

  async downloadOssCount(username: string) {
    try {
      let res = await client.get(`${username}/count/count.json`);
      const decoder = new TextDecoder("utf-8");
      const dataString = decoder.decode(res.content);
      return { result: { blob: dataString }, status: 200 };
    } catch (e) {
      if (e.code === "NoSuchKey") {
        return { blob: null };
      } else {
        throw e;
      }
    }
  }

  async downloadOssFile(path: string) {
    try {
      let res = await client.get(path);
      return res.content;
    } catch (e) {
      if (e.code === "NoSuchKey") {
        return null;
      } else {
        throw e;
      }
    }
  }

  async uploadOssFile(
    fileName: string,
    fileBuffer: Buffer,
    type: string,
    user: string
  ) {
    try {
      const client = new OSS({
        region: "oss-cn-hangzhou",
        accessKeyId: "LTAI5tFS1ACfWCnwrLhHkPB8",
        accessKeySecret: "Ec9OmNiZrFlFpQlLvpML3OIxyFFVlo",
        bucket: "ai-assistant-client",
        secure: true
      });
      let path = `${user}/${type}/${fileName}`;

      let blob = type === "count" ? Buffer.from(fileBuffer) : fileBuffer;
      client.put(path, blob);
      return "OK";
    } catch (e) {
      return e;
    }
  }
}
